package com.eqdd.yiqidian.ui.gongneng.car;

import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.view.View;

import com.eqdd.yiqidian.R;
import com.eqdd.yiqidian.RecyclerViewCustom;
import com.eqdd.yiqidian.RecyclerViewRefreshCustom;
import com.eqdd.yiqidian.adapter.slimadapter.SlimAdapterEx;
import com.eqdd.yiqidian.adapter.slimadapter.SlimInjector;
import com.eqdd.yiqidian.adapter.slimadapter.viewinjector.IViewInjector;
import com.eqdd.yiqidian.base.AppConstent;
import com.eqdd.yiqidian.base.BaseActivity;
import com.eqdd.yiqidian.base.Config;
import com.eqdd.yiqidian.bean.rebuild.CarListInfoBean;
import com.eqdd.yiqidian.bean.rebuild.ZhangPageResultBean;
import com.eqdd.yiqidian.helper.mvchelper.ModelRx2DataSource;
import com.eqdd.yiqidian.helper.mvchelper.Rx2DataSource;
import com.eqdd.yiqidian.http.DialogCallBack;
import com.eqdd.yiqidian.http.HttpConfig;
import com.eqdd.yiqidian.http.HttpResult;
import com.eqdd.yiqidian.http.JsonConverter;
import com.eqdd.yiqidian.ui.select.SelectTimeActivity;
import com.eqdd.yiqidian.utils.ToastUtil;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.lzy.okrx2.adapter.FlowableBody;
import com.shizhefei.mvc.MVCCoolHelper;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.Flowable;

/**
 * @author吕志豪 .
 * @date 17-11-22  下午4:09.
 * Github :https://github.com/lvzhihao100
 * E-Mail：1030753080@qq.com
 * 简书 :http://www.jianshu.com/u/6e525b929aac
 */

public class SelectCarActivity extends BaseActivity {

    private RecyclerViewRefreshCustom dataBinding;
    private SlimAdapterEx<CarListInfoBean> slimAdapterEx;
    private int pageNum = 0;
    private MVCCoolHelper<List<CarListInfoBean>> mvcHelper;
    private String startTime;
    private String endTime;
    private boolean isShowAll;

    @Override
    public void initBinding() {
        dataBinding = DataBindingUtil.setContentView(this, R.layout.activity_recyclerview_refresh);
        initTopTitleBar(View.VISIBLE, "选择车辆");

    }

    @Override
    public void initData() {
        isShowAll = getIntent().getBooleanExtra(Config.IS_SHOW_ALL, false);
        dataBinding.recyclerView.setLayoutManager(new LinearLayoutManager(this));
        slimAdapterEx = SlimAdapterEx.create().register(R.layout.list_item_10, new SlimInjector<CarListInfoBean>() {
            @Override
            public void onInject(CarListInfoBean data, IViewInjector injector) {
                injector.text(R.id.tv_upper_left_content, data.getVehicleType())
                        .text(R.id.tv_upper_right_content, data.getPlateNumber())
                        .text(R.id.tv_down_left_content, data.getSeats() + "个座位")
                        .image(R.id.iv_head, data.getPic1());

            }
        }).attachTo(dataBinding.recyclerView).updateData(new ArrayList());
        if (isShowAll) {
            ModelRx2DataSource<CarListInfoBean> dataSource = new ModelRx2DataSource<>(new ModelRx2DataSource.OnLoadSource() {
                @Override
                public Flowable<List> loadSource(int page, Rx2DataSource.DoneActionRegister register) {
                    pageNum = page == 1 ? 0 : pageNum;
                    return OkGo.<ZhangPageResultBean<List<CarListInfoBean>>>post(HttpConfig.BASE_URL + HttpConfig.CAR_LIST)
                            .params("page", pageNum)
                            .params("comid", AppConstent.user.getCompanyId())
                            .params("userGuid", AppConstent.user.getGuid())
                            .converter(new JsonConverter<ZhangPageResultBean<List<CarListInfoBean>>>() {
                                @Override
                                public void test() {
                                    super.test();
                                }
                            }).adapt(new FlowableBody<>())
                            .flatMap(listResultBean -> {
                                pageNum = listResultBean.getNextpage();
                                if (page == 1) {
                                    mvcHelper.setAutoLoadMore(true);
                                }
                                if (listResultBean.getStatus() == 200) {
                                    return Flowable.just(listResultBean.getItems() == null ? new ArrayList<CarListInfoBean>() : listResultBean.getItems());
                                } else {
                                    ToastUtil.showShort(listResultBean.getMsg());
                                    return Flowable.just(new ArrayList<>());
                                }
                            });

                }
            });
            slimAdapterEx.updateData(new ArrayList<>());
            mvcHelper = new MVCCoolHelper<>(dataBinding.coolRefreshView);
            mvcHelper.setDataSource(dataSource);
            mvcHelper.setAdapter(slimAdapterEx);
            mvcHelper.refresh();
        } else {
            String startTime = getIntent().getStringExtra(Config.START_TIME);
            String endTime = getIntent().getStringExtra(Config.END_TIME);
            if (!"".equals(startTime) && !"".equals(endTime)) {
                updateByTime(startTime, endTime);
            } else {
                initTopRightText("日期筛选", v -> {
                    startActivityForResult(SelectTimeActivity.class, null, Config.SELECT_TIME);
                });
                dataBinding.coolRefreshView.setEnabled(false);
            }

        }
        dataBinding.recyclerView.setSwipeItemClickListener((view, position) -> {
            Intent intent = new Intent();
            intent.putExtra(Config.BEAN, slimAdapterEx.getDataItem(position));
            intent.putExtra(Config.START_TIME, startTime);
            intent.putExtra(Config.END_TIME, endTime);
            setResult(Config.SUCCESS, intent);
            finish();
        });
    }

    @Override
    public void setView() {
        String startTime = getIntent().getStringExtra(Config.START_TIME);
        String endTime = getIntent().getStringExtra(Config.END_TIME);
        if (!"".equals(startTime) && !"".equals(endTime)){
            return;
        }
        if (!isShowAll) {
            Bundle bundle = new Bundle();
            bundle.putString(Config.TITLE, "选择用车时间");
            startActivityForResult(SelectTimeActivity.class, bundle, Config.SELECT_TIME);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Config.SUCCESS && requestCode == Config.SELECT_TIME) {
            startTime = data.getStringExtra(Config.START_TIME);
            endTime = data.getStringExtra(Config.END_TIME);
            updateByTime(startTime, endTime);
        } else {
            finish();
        }
    }

    private void updateByTime(String startTime, String endTime) {
        OkGo.<HttpResult<List<CarListInfoBean>>>post(HttpConfig.BASE_URL + HttpConfig.CAR_LIST_BY_TIME)
                .params("comid", AppConstent.user.getCompanyId())
                .params("startTime", startTime)
                .params("endTime", endTime)
                .execute(new DialogCallBack<HttpResult<List<CarListInfoBean>>>(SelectCarActivity.this) {
                    @Override
                    public void onSuccess(Response<HttpResult<List<CarListInfoBean>>> response) {
                        HttpResult<List<CarListInfoBean>> httpResult = response.body();
                        ToastUtil.showShort(httpResult.getMsg());
                        if (httpResult.getStatus() == 200) {
                            slimAdapterEx.updateData(httpResult.getItems());
                        }
                    }
                });
    }
}
